package server;

import java.io.*;

/**
 * 自定义类加载器，用于加载webapps目录下的各个项目
 */
public class WebappClassLoader extends ClassLoader {
    /**
     * 项目路径
     */
    private String packagePath;

    /**
     * 构造WebappClassLoader对象
     *
     * @param packagePath 项目路径
     */
    public WebappClassLoader(String packagePath) {
        super(Thread.currentThread().getContextClassLoader());
        this.packagePath = packagePath;
    }

    /**
     * 加载指定的类
     *
     * @param name 类路径
     * @return 加载的类
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classPath = name.replaceAll("\\.", "/");

        try {
            InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream(String.format("%s/%s.class", packagePath, classPath));
            byte[] code = new byte[inputStream.available()];

            inputStream.read(code);
            return defineClass(name, code, 0, code.length);
        } catch (IOException ex) {
            throw new ClassNotFoundException();
        }
    }
}
